/*
 * File:   mainForm.cpp
 * Author: f10-kafedra
 *
 * Created on 6 Сентябрь 2011 г., 10:13
 */

#include "mainForm.h"



mainForm::mainForm() {
    mainWindow.setupUi(this);
    setup();
    
    //run();
}

mainForm::~mainForm() {
    
    //delete srvResp;
    //client->unloginFromBase();
}

void mainForm::setup()
{
    timer = new QTimer(this);
    timer->setInterval(100);
    timer->connect(timer, SIGNAL(timeout()), this, SLOT(slotTimerCheckState()));
    
}

void mainForm::slotUserRequest()
{
    if (mainWindow.rbFamily->isChecked())
    { // поиск по ФИО
        client->getUser_FIO(mainWindow.leSearch->text(), mainWindow.leMaxMFN->text());
        client->structRequest.lastRequest = GET_USER_BY_FIO;
    }
    else 
    { // поиск по MFN
        client->getUser_MFN(mainWindow.leSearch->text(), mainWindow.leMaxMFN->text());
        client->structRequest.lastRequest = GET_USER_BY_MFN;
    }
}



void mainForm::run()
{
    stateChanged = true;
    timer->start();
    
    //client->structRequest.lastRequest = LOGIN;
    //client->getConfFile("goroda.mnu");
    //client->structRequest.lastRequest = GET_FILE_CITY;

}

void mainForm::slotTimerCheckState()
{
    if (client->inWork)
    {
        if (stateChanged)
        {
            cout << "server busy" << endl;
            stateChanged = false;
        }
    }
    else
    {
        switch (client->structRequest.lastRequest)
        {
            case LOGIN:
            {
                if (!started)
                {   
                    cout << "app started" << endl;
                    
                    
                    switch (apm)
                    {
                        case APM_REGUSER:
                        {
                            client->request.operation = GET_FILE_CITY;
                            client->getConfFile("goroda.mnu");
                            break;
                        }
                        case APM_INFO:
                        {
                        
                            client->structRequest.lastRequest = IDLE;
                            break;
                        }
                    }
                    started = true;
                }
                else
                {
                    //cout << "operational do" << endl;
                }
                    
                
                //client->structRequest.lastRequest = GETMAXMFN;
                break;
            }
            case GETMAXMFN:
            {

                break;
            }
            case SERVER_VERSION:
            {
                client->structRequest.lastRequest = IDLE;
                mainWindow.leUsersOnline->setText(srvResp->parseServerVersion(client->lastBuffer));
                break;
            }
            case GET_USER_BY_FIO:
            {
                //mainWindow.teRawData->setText(client->lastBuffer);
                client->structRequest.lastRequest = IDLE;
                //mainWindow.teClearedData->setText(srvResp->parseUserData(client->lastBuffer));
                cout << "get user by fio" << endl;
                cout << client->lastBuffer.toAscii().data() << endl;
                break;
            }
            case GET_USER_BY_MFN:
            {
                mainWindow.teRawData->setText(client->lastBuffer);
                client->structRequest.lastRequest = IDLE;
                //mainWindow.teClearedData->setText(srvResp->parseUserData(client->lastBuffer));
                break;
            }
            case CREATE_USER:
            {
                //mainWindow.teRawData->setText(client->lastBuffer);
                cout << "this is create user switch" << endl;
                //client->getLastID();
                //client->structRequest.lastRequest = IDLE;
                break;
            }
            case GET_LOGIC_DEL:
            {
                //mainWindow.teRawData->setText(client->lastBuffer);
                client->maxID = srvResp->parseLastID(client->lastBuffer);
                //cout << "max id: " << client->maxID.toAscii().data() << endl;
                //client->request.operation = IDLE;
                client->structRequest.lastRequest = IDLE;
                break;
            }
            case GET_FILE_CITY:
            {
//                cout << "goroda:\n" << client->lastBuffer.toAscii().data() << endl;
                client->configFiles.city = client->lastBuffer;
                client->configFiles.filled = true;
                
                if (!client->singleRequest)
                {
                    client->request.operation = GET_FILE_STREET;
                    client->getConfFile("ulici.mnu");
                }
                
//                client->structRequest.lastRequest = IDLE;
                break;
            }
            case GET_FILE_STREET:
            {
                client->configFiles.street = client->lastBuffer;
                client->configFiles.filled = true;
                if (!client->singleRequest)
                {
                    client->request.operation = GET_FILE_STUDY;
                    client->getConfFile("uchebniezav.mnu");
                }
                //client->structRequest.lastRequest = GET_FILE_STUDY;
                break;
            }
            case GET_FILE_STUDY:
            {
                client->configFiles.study = client->lastBuffer;
//                client->getOVD();
//                client->structRequest.lastRequest = GET_FILE_OVD;
                client->configFiles.filled = true;
                client->structRequest.lastRequest = IDLE;
                client->unloginFromBase();
                break;
            }
            case GET_FILE_OVD:
            {
                client->configFiles.OVD = client->lastBuffer;
                //cout << client->lastBuffer.toAscii().data() << endl;
                client->configFiles.filled = true;
                client->structRequest.lastRequest = IDLE;
                break;
            }
            case CHECK_USER_EXISTS:
            {
                client->lastOperResult.oper = CHECK_USER_EXISTS;
                switch (srvResp->parseExistUser(client->lastBuffer))
                {
                    case true:
                    {
                        client->lastOperResult.result = 1;
                        break;
                    }
                    case false:
                    {
                        client->lastOperResult.result = 0;
                        break;
                    }
                //client->structRequest.lastRequest = IDLE;
                }
                break;
            }
            case GET_TARGET_INFO:
            {
                //cout << "response size" << client->lastBuffer.length() << endl;
                QTextCodec::setCodecForCStrings(QTextCodec::codecForName("cp1251"));
                client->inform = srvResp->parseTargetInfo(client->lastBuffer);
                //for (int i = 0; i < client->buffer.size(); i++)
//                    cout << client->buffer.at(i).toAscii().data() << endl;
                //cout << client->lastBuffer.toAscii().data() << endl;
                
                client->structRequest.lastRequest = IDLE;
                break;
            }
            case GET_INFO_BY_FIELDS:
            {
                QTextCodec::setCodecForCStrings(QTextCodec::codecForName("cp1251"));
                cout << client->lastBuffer.toAscii().data() << endl;
                
                client->structRequest.lastRequest = IDLE;
                break;
            }
            
            case GET_USER_BY_ID:
            {
                //QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
                cout << "tryng get buffer:\n" << /*client->lastBuffer.toAscii().data() <<*/ endl;
                //srvResp->parseUserGettedByID(client->lastBuffer);
                client->structRequest.lastRequest = IDLE;
                break;
            }
            case GET_RECORD:
            {
                //cout << client->lastBuffer.toAscii().data();
                cout << "getted record" << endl;
                client->structRequest.lastRequest = IDLE;
                break;
            }
            
            case UPDATE_RECORD:
            {
                cout << "updated" << endl;
                client->lastOperResult.result = 0;
                //cout << client->lastBuffer.toAscii().data();
                client->structRequest.lastRequest = IDLE;
                //client->lastBuffer.clear();
                break;
            }
            
            case IDLE:
            {
            
                break;
            }
            
            default:
            {
                
                //cout << "can use" << endl;
                break;
            }
        
        }
        
        if (!client->query.empty())
        {
#ifdef DEBUG_OUTPUT            
//            cout << "sending this type data:\n" << client->query.front().req.toAscii().data() << endl;
            cout << "query size: " << client->query.size()<< endl;
            cout << "current operation: " << currentOperation(client->query.front().operation) << endl;
#endif            
            if (client->query.front().operation == CREATE_USER)
                client->query.front().req.append("30#" + client->maxID + QString::fromAscii(QByteArray::fromHex("1F1E").data()));
            
            if (client->__sendData(client->query.front().req.toStdString()) == true)
                client->__reciveAnswer();
            
            client->structRequest.lastRequest = client->query.front().operation;
            client->query.erase(client->query.begin());
        }
    }
}

void mainForm::slotManualRequestChanged()
{
    QString tmpManualRequest = mainWindow.teManualRequest->toPlainText();
    tmpManualRequest.remove(QRegExp("^\\d+")); // удаляем длину запроса
//    tmpManualRequest.prepend(QString::number(tmpManualRequest.length()) + '\n');
    QString tmp = tmpManualRequest.replace("\\n", "\n", Qt::CaseInsensitive);
    mainWindow.teRawDataOnServer->setText(tmp.prepend(QString::number(tmp.length()) + '\n'));
}

void mainForm::slotSendManualRequest()
{
    if (mainWindow.teRawDataOnServer->toPlainText().length() > 0)
    {
        client->loginToBase();
        client->sendData(mainWindow.teRawDataOnServer->toPlainText());
        client->structRequest.lastRequest = GET_USER_BY_MFN;
        client->unloginFromBase();
    }
}

char* mainForm::currentOperation(request req)
{
    switch (req)
    {
        case LOGIN:
        {
            return (char*)"LOGIN";
            break;
        }
        
        case UNLOGIN:
        {
            return (char*)"UNLOGIN";
            break;
        }
        
        case GET_USER_BY_ID:
        {
            return (char*)"GET_USER_BY_ID";
            break;
        }
        
        default:
        {
            return (char*)"UNDEFINED OPERATION";
            break;
        }
    }
}